package com.df.happylearn.request;

import com.android.volley.Cache;
import com.android.volley.NetworkResponse;
import com.android.volley.toolbox.HttpHeaderParser;
import com.df.happylearn.R;
import com.df.happylearn.application.MyApplication;

import java.util.Map;

public class CachedHttpHeaderParser {

    //忽略headers里的缓存控制信息，强制设置缓存信息
    public static Cache.Entry parseIgnoreCacheHeaders(NetworkResponse response) {
        long now = System.currentTimeMillis();

        Map<String, String> headers = response.headers;
        long serverDate = 0;
        String serverEtag = null;
        String headerValue;

        headerValue = headers.get("Date");
        if (headerValue != null) {
            serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
        }

        serverEtag = headers.get("ETag");

        final long cacheHitButRefreshed = Integer.valueOf(MyApplication.getInstance().getResources().getInteger(R.integer.time_cacheHitButRefreshed)).longValue()
                * 1000; // in X seconds cache will be hit, but also refreshed on background
        final long cacheExpired = Integer.valueOf(MyApplication.getInstance().getResources().getInteger(R.integer.time_cacheExpired)).longValue()
                *1000;// in X  seconds this cache entry expires completely
        final long softExpire = now + cacheHitButRefreshed;
        final long ttl = now + cacheExpired;

        Cache.Entry entry = new Cache.Entry();
        entry.data = response.data;
        entry.etag = serverEtag;
        entry.softTtl = softExpire;
        entry.ttl = ttl;
        entry.serverDate = serverDate;
        entry.responseHeaders = headers;

        return entry;
    }
}
